package chaoyue.study.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * FutureTask
 * FutureTask可以用来处理带返回值的任务，不过现在已经被CompletableFuture取代了。了解一下就行
 */
public class FutureTaskTest {
    public static void main(String[] args) throws Exception {
        long startTime = System.currentTimeMillis();
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        FutureTask<String> task1 = new FutureTask<>(() -> {
            TimeUnit.MILLISECONDS.sleep(500);
            return "task1 overt";
        });
        threadPool.submit(task1);
        FutureTask<String> task2 = new FutureTask<>(() -> {
            TimeUnit.MILLISECONDS.sleep(300);
            return "task2 overt";
        });
        threadPool.submit(task2);
        FutureTask<String> task3 = new FutureTask<>(() -> {
            TimeUnit.MILLISECONDS.sleep(200);
            return "task3 overt";
        });
        threadPool.submit(task3);
        // 阻塞获取结果
        System.out.println(task3.get());
        System.out.println(task2.get());
        System.out.println(task1.get());

        // 总耗时应该差不多约等于最长那个任务的耗时
        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        System.out.println("总耗时：" + totalTime);
        threadPool.shutdown();
    }
}
